package com.papercutting.platform.filter;

import com.papercutting.platform.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

/**
 * JWT认证过滤器
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        
        // 获取请求路径
        String path = request.getRequestURI();
        System.out.println("请求路径: " + path);
        
        // 允许匿名访问的路径
        if (path.startsWith("/api/auth/login") || 
            path.startsWith("/api/auth/web-login") ||
            path.startsWith("/api/health") || 
            path.startsWith("/api/info") ||
            path.startsWith("/error") ||
            path.startsWith("/uploads/") ||
            path.startsWith("/images/") ||
            path.startsWith("/static/") ||
            path.startsWith("/api/banner/active") ||
            path.startsWith("/api/carousel/") ||
            path.startsWith("/api/home/") ||
            path.startsWith("/api/culture/") ||
            path.startsWith("/api/tutorial/") ||
            path.startsWith("/api/tutorial-step/") ||
            path.startsWith("/api/news/") ||
            path.startsWith("/api/search/")) {
            System.out.println("允许匿名访问的路径");
            filterChain.doFilter(request, response);
            return;
        }
        
        // 从请求头中获取token
        String authorizationHeader = request.getHeader("Authorization");
        System.out.println("Authorization头: " + authorizationHeader);
        
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            try {
                String token = authorizationHeader.substring(7);
                System.out.println("解析的token: " + token);
                // 验证token有效性
                String username = jwtUtil.getUsernameFromToken(token);
                System.out.println("从token中获取的用户名: " + username);
                
                if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                    // 验证token是否有效
                    if (jwtUtil.validateToken(token, username)) {
                        // 获取用户类型并设置权限
                        List<GrantedAuthority> authorities = new ArrayList<>();
                        Integer userType = jwtUtil.getUserTypeFromToken(token);
                        System.out.println("从token中获取的用户类型: " + userType);
                        
                        if (userType != null && userType == 1) {
                            // 管理员用户
                            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
                            authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
                        } else {
                            // 普通用户
                            authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
                        }
                        
                        // 创建认证对象
                        UsernamePasswordAuthenticationToken authenticationToken = 
                            new UsernamePasswordAuthenticationToken(username, null, authorities);
                        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        
                        // 将认证对象设置到安全上下文中
                        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                        
                        // 将用户ID添加到请求属性中
                        Long userId = jwtUtil.getUserIdFromToken(token);
                        System.out.println("从token中获取的用户ID: " + userId);
                        request.setAttribute("userId", userId);
                    }
                }
            } catch (Exception e) {
                System.out.println("Token解析异常: " + e.getMessage());
            }
        }
        
        filterChain.doFilter(request, response);
    }
}